<template>
  <div class="login">
    <!-- 登录页内容 -->
    <div class="login-form">
      <!--      登录表单-->
      <el-form v-if="isLogin" ref="loginFormRef" :model="loginFormData" :rules="rules">
        <div class="form-title">
          <h2>{{ defaultSettings.title }}</h2>
        </div>
        <!-- 职工号 -->
        <el-form-item prop="staffId">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <User />
            </el-icon>
            <el-input
              ref="staffId"
              v-model="loginFormData.staffId"
              placeholder="请输入职工号"
              name="staffId"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <Lock />
            </el-icon>
            <el-input
              v-model="loginFormData.password"
              placeholder="请输入密码"
              type="password"
              name="password"
              size="large"
              class="h-[48px] pr-2"
              show-password
            />
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-button :loading="loading" type="primary" size="large" class="w-full" @click="login">
          登 录
        </el-button>
      </el-form>
      <!--      注册表单-->
      <el-form v-else ref="registerFormRef" :model="registerFormData" :rules="rules">
        <div class="form-title">
          <h2>{{ defaultSettings.title }}</h2>
        </div>
        <!--        姓名-->
        <el-form-item prop="name">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <User />
            </el-icon>
            <el-input
              ref="name"
              v-model="registerFormData.teaName"
              placeholder="请输入姓名"
              name="name"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>
        <!-- 职工号 -->
        <el-form-item prop="staffId">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <User />
            </el-icon>
            <el-input
              ref="staffId"
              v-model="registerFormData.staffId"
              placeholder="请输入职工号"
              name="staffId"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>
        <el-form-item prop="gender">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <User />
            </el-icon>
            <el-input
              ref="name"
              v-model="registerFormData.teaSex"
              placeholder="请输入性别"
              name="name"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>
        <el-form-item prop="phone">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <User />
            </el-icon>
            <el-input
              ref="name"
              v-model="registerFormData.teaPhone"
              placeholder="请输入电话"
              name="name"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>
        <el-form-item prop="phone">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <User />
            </el-icon>
            <el-input
              ref="email"
              v-model="registerFormData.teaEmail"
              placeholder="请输入邮箱"
              name="name"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <Lock />
            </el-icon>
            <el-input
              v-model="registerFormData.password"
              placeholder="请输入密码"
              type="password"
              name="password"
              size="large"
              class="h-[48px] pr-2"
              show-password
            />
          </div>
        </el-form-item>
        <!--        确认密码-->
        <el-form-item prop="confirmPassword">
          <div class="input-wrapper">
            <el-icon class="mx-2">
              <Lock />
            </el-icon>
            <el-input
              v-model="registerFormData.checkPassword"
              placeholder="请输再次入密码"
              type="password"
              name="confirmPassword"
              size="large"
              class="h-[48px] pr-2"
              show-password
            />
          </div>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-button :loading="loading" type="primary" size="large" class="w-full" @click="register">
          注册
        </el-button>
      </el-form>
      <!--      登录注册切换-->
      <div v-if="isLogin" class="change">
        <p>
          新用户？去
          <a @click="changeStatus">注册</a>
        </p>
      </div>
      <div v-else class="change">
        <p>
          已有账户？去
          <a @click="changeStatus">登录</a>
        </p>
      </div>
    </div>

    <!-- 登录页底部 -->
    <div class="login-footer">
      <el-text size="small">c-Teaching-Management</el-text>
    </div>
  </div>
</template>

<script setup lang="ts">
import { type LoginFormData } from "@/api/auth";
import router from "@/router";
import type { FormInstance } from "element-plus";
import defaultSettings from "@/settings";
import { reactive } from "vue";
import { Lock } from "@element-plus/icons-vue";
import { setAccessToken } from "@/utils/auth";
import { teacherLogin, teacherRegister } from "@/api/user/user";
import { useUserStoreHook } from "@/store";

// 是否是登录
const isLogin = ref(true);
const loginFormRef = ref<FormInstance>();
const registerFormRef = ref<FormInstance>();
const loading = ref(false);
// 切换登录/注册
const changeStatus = () => {
  isLogin.value = !isLogin.value;
};
const loginFormData = reactive<LoginFormData>({
  staffId: "10001",
  password: "123456",
});
const registerFormData = reactive({
  teaName: "",
  staffId: "",
  teaSex: "",
  teaEmail: "",
  teaPhone: "",
  password: "",
  checkPassword: "",
});
// 自定义验证：确认密码是否与密码一致
const validateConfirmPass = (rule: any, value: string, callback: any) => {
  if (value !== registerFormData.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};
const rules = reactive({
  teaName: [
    {
      required: true,
      message: "请输入姓名",
      trigger: "blur",
    },
  ],
  staffId: [
    {
      required: true,
      message: "请输入职工号",
      trigger: "blur",
    },
  ],
  teaSex: [
    {
      required: true,
      message: "请输入性别",
      trigger: "blur",
    },
  ],
  teaEmail: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
  ],
  teaPhone: [
    {
      required: true,
      message: "请输入电话",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
  checkPassword: [
    {
      required: true,
      message: "请再次输入密码",
      trigger: "blur",
    },
    {
      validator: validateConfirmPass,
      trigger: "blur",
    },
  ],
});
// 登录
const login = () => {
  if (!loginFormRef.value) return;
  loading.value = true;
  loginFormRef
    .value!.validate()
    .then(async () => {
      const accessToken = await teacherLogin(loginFormData);
      setAccessToken(accessToken);
      await router.push("/");
    })
    .finally(() => {
      loading.value = false;
    });
};
// 注册
const register = async () => {
  if (!registerFormRef.value) return;
  loading.value = true;
  try {
    // 1. 调用注册接口
    await teacherRegister(registerFormData);
    // 2. 使用注册信息立即进行登录（模拟自动登录）
    const accessToken = await teacherLogin({
      staffId: registerFormData.staffId,
      password: registerFormData.password,
    });
    // 3. 设置 token 到本地存储
    setAccessToken(accessToken);
    // 4. 更新登录状态
    const userStore = useUserStoreHook();
    userStore.isLogin = true;
    await router.push("/");
    ElMessage.success("注册成功");
  } catch (error) {
    console.error("注册或自动登录失败:", error);
    ElMessage.error("注册失败或自动登录失败，请检查输入内容");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  background: url("@/assets/images/login-bg.jpg") no-repeat center right;

  .login-header {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: right;
    width: 100%;
    padding: 15px;

    .logo {
      width: 26px;
      height: 26px;
    }

    .title {
      margin: auto 5px;
      font-size: 24px;
      font-weight: bold;
      color: #3b82f6;
    }
  }

  .login-form {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 460px;
    padding: 40px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: var(--el-box-shadow-light);

    @media (width <= 460px) {
      width: 100%;
      padding: 20px;
    }

    .form-title {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 0 20px;
      text-align: center;
    }

    .input-wrapper {
      display: flex;
      align-items: center;
      width: 100%;
    }

    .captcha-img {
      height: 48px;
      cursor: pointer;
      border-top-right-radius: 6px;
      border-bottom-right-radius: 6px;
    }

    .third-party-login {
      display: flex;
      justify-content: center;
      width: 100%;
      color: var(--el-text-color-secondary);

      *:not(:first-child) {
        margin-left: 20px;
      }

      .icon {
        cursor: pointer;
      }
    }
  }
  .change {
    p {
      margin-bottom: 5px;
      font-size: 14px;
      color: darkgray;
      a {
        color: #3b82f6;
      }
    }
    position: absolute;
    bottom: 1px;
    right: 40px;
  }

  .login-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 10px 0;
    text-align: center;
  }
}

:deep(.el-form-item) {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

html.dark {
  .login {
    background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;

    .login-form {
      background: transparent;
      box-shadow: var(--el-box-shadow);
    }
  }
}
</style>
